package _18_剑指OfferII;

import _18_剑指OfferII.datastrcute.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class _044_剑指OfferII二叉树每层的最大值 {

    // 二叉树层序遍历
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> maxList = new ArrayList<>();
        if (root == null) return maxList;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            int max = queue.peek().val;
            while (size-- > 0) {
                TreeNode node = queue.poll();
                max = Math.max(max, node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            maxList.add(max);
        }
        return maxList;
    }

}
